<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    title="购买理财产品"
    width="600px"
    @opened="onDialogOpened"
    @closed="onDialogClosed"
  >
    <div class="purchase-content" v-if="product">
      <div class="product-summary">
        <h4>{{ product.name }}</h4>
        <div class="summary-info">
          <div class="info-item">
            <span>预期年化收益率：</span>
            <span class="highlight">{{ formatRate(product.expectedReturn) }}%</span>
          </div>
          <div class="info-item">
            <span>投资期限：</span>
            <span>{{ product.duration }}天</span>
          </div>
          <div class="info-item">
            <span>起购金额：</span>
            <span>¥{{ formatAmount(product.minAmount) }}</span>
          </div>
          <div class="info-item">
            <span>风险等级：</span>
            <span>{{ getRiskLevelText(product.riskLevel) }}</span>
          </div>
        </div>
      </div>

      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="投资金额" prop="amount">
          <el-input
            v-model="form.amount"
            placeholder="请输入投资金额"
            type="number"
            :min="product.minAmount"
            ref="amountInputRef"
          >
            <template #append>元</template>
          </el-input>
          <div class="amount-hints">
            <span>最小投资金额：¥{{ formatAmount(product.minAmount) }}</span>
            <span>可用余额：¥{{ formatAmount(userBalance) }}</span>
          </div>
        </el-form-item>
        <el-form-item label="预期收益" v-if="expectedProfit">
          <div class="expected-profit">
            <span class="profit-amount">¥{{ formatAmount(expectedProfit) }}</span>
            <span class="profit-tip">（预期收益，实际收益可能存在差异）</span>
          </div>
        </el-form-item>
        <el-form-item label="支付密码" prop="paymentPassword">
          <el-input
            v-model="form.paymentPassword"
            type="password"
            placeholder="请输入支付密码"
            maxlength="20"
            show-password
            autocomplete="new-password"
          />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('update:visible', false)">取消</el-button>
        <el-button type="primary" @click="confirmPurchase" :loading="loading">
          确认购买
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, nextTick, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { formatAmount, formatRate, getRiskLevelText } from './utils';

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  product: {
    type: Object,
    default: null
  },
  userBalance: {
    type: Number,
    default: 0
  }
});

const emit = defineEmits(['update:visible', 'confirm']);

// 表单数据
const form = reactive({
  amount: '',
  paymentPassword: ''
});

const formRef = ref(null);
const amountInputRef = ref(null);
const loading = ref(false);

// 动态计算预期收益
const expectedProfit = computed(() => {
  if (!props.product || !form.amount) return 0;
  const amount = parseFloat(form.amount);
  const rate = parseFloat(props.product.expectedReturn) / 100;
  const days = parseInt(props.product.duration);
  return (amount * rate * days) / 365;
});

// 表单验证规则
const rules = {
  amount: [
    { required: true, message: '请输入投资金额', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入投资金额'));
        } else if (parseFloat(value) < parseFloat(props.product?.minAmount || 0)) {
          callback(new Error(`最小投资金额为¥${formatAmount(props.product?.minAmount || 0)}`));
        } else if (parseFloat(value) > props.userBalance) {
          callback(new Error(`投资金额不能超过账户余额¥${formatAmount(props.userBalance)}`));
        } else {
          callback();
        }
      }, 
      trigger: 'blur' 
    }
  ],
  paymentPassword: [
    { required: true, message: '请输入支付密码', trigger: 'blur' },
    { min: 6, max: 20, message: '支付密码长度在6到20个字符', trigger: 'blur' }
  ]
};

// 弹窗事件处理
const onDialogOpened = () => {
  // 弹窗打开后自动聚焦到金额输入框
  nextTick(() => {
    if (amountInputRef.value) {
      amountInputRef.value.focus();
    }
  });
};

const onDialogClosed = () => {
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.amount = '';
  form.paymentPassword = '';
  loading.value = false;
};

// 确认购买
const confirmPurchase = async () => {
  if (!formRef.value) return;
  
  loading.value = true;
  
  try {
    // 表单验证
    await formRef.value.validate();
    
    // 用户确认
    await ElMessageBox.confirm(
      `确认购买「${props.product.name}」，投资金额¥${formatAmount(form.amount)}？`,
      '确认购买',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    const data = {
      productId: props.product.id,
      amount: parseFloat(form.amount),
      paymentPassword: form.paymentPassword
    };
    
    console.log('PurchaseDialog 发送购买数据:', data);
    emit('confirm', data);
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('表单验证失败：', error);
      ElMessage.error('表单验证失败');
    }
    loading.value = false;
  }
  // 注意：成功情况下的loading状态由父组件处理
};
</script>

<style scoped>
.purchase-content {
  padding: 8px;
}

.product-summary {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
}

.product-summary h4 {
  margin: 0 0 12px 0;
  font-size: 18px;
  color: #303133;
}

.summary-info {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.info-item .highlight {
  color: #e6a23c;
  font-weight: 600;
}

.amount-hints {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.expected-profit {
  display: flex;
  align-items: center;
  gap: 8px;
}

.profit-amount {
  font-size: 18px;
  font-weight: 600;
  color: #67c23a;
}

.profit-tip {
  font-size: 12px;
  color: #909399;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .summary-info {
    grid-template-columns: 1fr;
  }
}
</style>
